package leetcode.每日一题;

import org.apache.poi.ss.formula.functions.T;
import org.junit.Test;

/**
 * @author :songyaozhang
 * @date :Created 2021/7/27 19:24
 * @description :https://leetcode-cn.com/problems/second-minimum-node-in-a-binary-tree/
 */
public class 二叉树中第二小的节点 {
    @Test
    public void test() {
        Solution solution = new Solution();
        System.out.println(solution.findSecondMinimumValue(new TreeNode(2, new TreeNode(2, null, null)
                , new TreeNode(2, null, null))));
    }


    //Definition for a binary tree node.
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    class Solution {
        public int findSecondMinimumValue(TreeNode root) {
            long res = findSecondMinimumValue0(root);
            if (res == Long.MAX_VALUE) return -1;
            return (int) res;
        }
        private long findSecondMinimumValue0(TreeNode tar) {
            if (tar.left == null) return Long.MAX_VALUE;

            if (tar.left.val != tar.right.val) return Math.min(
                    Math.max(tar.left.val, tar.right.val),
                    findSecondMinimumValue0(tar.left.val > tar.right.val ? tar.right : tar.left));
            return Math.min(findSecondMinimumValue0(tar.left), findSecondMinimumValue0(tar.right));
        }
    }




}
